package com.demo.rpc.client;

import com.demo.rpc.common.RpcRequest;
import com.demo.rpc.common.RpcResponse;

import java.io.*;
import java.net.Socket;

public class RpcClient {

    public Object start(RpcRequest request, String host, int port) throws Throwable {
        Socket server = new Socket(host, port);
        InputStream in = null;
        ObjectInputStream oin = null;
        OutputStream out = null;
        ObjectOutputStream oout = null;
        try {
            //1.发送请求数据
            out = server.getOutputStream();
            oout = new ObjectOutputStream(out);
            oout.writeObject(request);
            oout.flush();
            // 2. 获取返回数据
            in = server.getInputStream();
            oin = new ObjectInputStream(in);
            Object res = oin.readObject();
            RpcResponse response = null;
            if (!(res instanceof RpcResponse)) {
                throw new RuntimeException("返回参数错误");
            } else {
                response = (RpcResponse) res;
            }
            // 3. 返回结果
            if (response.getError() != null) {
                throw response.getError();
            }
            return response.getResult();
        } finally {
            try {
                if (in != null) in.close();
                if (oin != null) oin.close();
                if (out != null) out.close();
                if (oout != null) oout.close();
                if (server != null) server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
